package com.jfinal.weixin.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.weixin.model.WxVote;
import com.sun.jmx.snmp.Timestamp;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.Random;

/**
 * Created by 446705260@qq.com on 16/6/1.
 * chengzhichao
 */
public class ShfController extends Controller{
    public static int vote(int voteid, int babyid, int max, int min) {
        int result = 0;
        int a = Db.find("select id from wxvote where babyid="+babyid).size();
        if(a>=(max-min)){
            return 1;
        }
        Random random = new Random();
        int i = random.nextInt(max) % (max - min + 1) + min;
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://vote.weixin.shenghuofan.com//index.php?s=/Home/Cfvote/vote/id/" + voteid + ".html");
        StringEntity reqEntity;
        try {
            reqEntity = new StringEntity("baby_id=" + babyid + "&vote_num=0&rule_id=");
            reqEntity.setContentType("applications/x-www-form-urlencoded");
            httppost.setEntity(reqEntity);
            httppost.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            httppost.setHeader("X-Requested-With", "XMLHttpRequest");
            httppost.setHeader("Accept-Encoding", "gzip, deflate");
            httppost.setHeader("Accept-Language", "zh-cn");
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httppost.setHeader("Origin", "http://vote.weixin.shenghuofan.com");
            httppost.setHeader("Connection", "keep-alive");
            httppost.setHeader("User-Agent",
                    "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13D15");
            httppost.setHeader("Referer", "http://vote.weixin.shenghuofan.com/index.php?s=/Home/Cfvote/index/id/"
                    + voteid + "/sort/vote.html");
            httppost.setHeader("Cookie", "uid=1" + i + "5;deviceid=4" + i
                    + "58CC-3407-428A-AA40-CCD9CF035341;__cfduid=d8618e9f1c3b938bc612748c471cebdd6146"+i+"1915; clienttype=iOS;  PHPSESSID=u48sdi8h2jctfoldp0jc0fe136;shenghuofan=ANTbWzf1nOMgNQjzwJxIsYFT2Tc3wE6dVCEvCLOHd8vdLZ0dyBU7dF6VqqGIhOGJ9VYOGnekCL6N5e98wDdrs7kYEJKSZII75xgtREbEa%2Ba0aU0MOZdZ4GlG7u1cLKQgvHLTuIBQYjUYYjXiflWg6/w71qlvw60sqL9FsqDj7H3GXWw%2BCSvoAP2MzpporxLZkwpMrkCaSobsvmos9CXhxM7LHI8pswGJaml%2B5VzCoHg=; siteid=10;  version=2.0.6");
            HttpResponse response;
            response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                System.out.println(line);
            }
            if (sb.toString().contains("qR")) {
                result=2;
            }else if(sb.toString().contains("安全检查")){
                result=888;
            }else{
                WxVote w = new WxVote();
                w.set("babyid",babyid).set("voteid",voteid).set("time", new Timestamp().getDate()).save();
                result=a+3;
            }
            if (entity != null) {
                entity.consumeContent();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            result = 0;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }



    public String getresult(int result){
        String txt="";
        switch (result) {
            case 0:
                txt ="网络有点问题，等下再试";
                break;
            case 1:
                txt ="今天不要再试了，次数已用完";
                break;
            case 2:
                txt ="抽到重复的人了，再来一次";
                break;
            case 888:
                txt ="安全检查,暂时不能刷了";
                break;
            default:
                txt ="成功，你已经投票了"+(result-2)+"次";
                break;
        }
        return txt;
    }


    public  void test(){
        int result = vote(49,258,999,100);
        renderText(getresult(result));
    }
}
